from django.shortcuts import render
from django.views.generic import View
from apps.news.models import NewsCategory,News
from utils import restful
from apps.cms.forms import WriteNewsForm
from django.views.decorators.http import require_POST,require_GET
import qiniu
from django.core.paginator import Paginator
from datetime import datetime
from django.utils.timezone import make_aware
from urllib import parse
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import permission_required
# Create your views here.
def index(request):
    return render(request,'cms/index.html')

@method_decorator(permission_required(perm="news.view_news",login_url='/'),name='dispatch')
class NewsList(View):
    #http://127.0.0.1/cms/news_list/?p=3&start=''&end=''&cate
    def get(self,request):
        page = int(request.GET.get('p',1))
        start = request.GET.get('start')
        end = request.GET.get('end')
        title = request.GET.get('title')
        category_id = int(request.GET.get('category',0) or 0)
        newses = News.objects.select_related('category','author')

        if start or end:
            if start:
                start_date = datetime.strptime(start,'%Y/%m/%d')
                print(start_date)
            else:
                start_date = datetime(year=2018,month=6,day=1)

            if end:
                end_date = datetime.strptime(end, '%Y/%m/%d')
                print(end_date)
            else:
                end_date = datetime.today()
            newses = newses.filter(pub_time__range=(make_aware(start_date),make_aware(end_date)))
        if title:
            newses = newses.filter(title__icontains=title)
        if category_id:
            newses = newses.filter(category=category_id)
        paginator = Paginator(newses,2)
        page_obj = paginator.page(page)

        context_data  = self.get_pagination_data(paginator,page_obj)
        context = {
            # 'newses':newses,
            'newses':page_obj.object_list,#文章通过分页的形式展示
            'paginator':paginator,
            'page_obj':page_obj,
            'categories':NewsCategory.objects.all(),
            'start':start,
            'end':end,
            'category_id':category_id,
            'title':title,
            'url_query':'&'+parse.urlencode( {   #将字典转成 &start=1&end=10&title=kangbazi
                'start': start or '',
                'end': end or '',
                'title': title or '',
                'category': category_id or '',
            })
        }
        context.update(context_data)
        return render(request,'cms/news_list.html',context=context)
    def get_pagination_data(self,paginator,page_obj,around_count=2):
        current_page = page_obj.number # 当前页码
        num_pages = paginator.num_pages #总共多少页


        left_has_more = False
        right_has_more = False
        if current_page <= around_count+2:
            left_pages = range(1,current_page)
        else:
            left_has_more = True
            left_pages= range(current_page-around_count,current_page)

        if current_page >=  num_pages-around_count-1:
            right_pages = range(current_page+1,num_pages+1)
        else:
            right_has_more = True
            right_pages= range(current_page+1,current_page+around_count+1)
        return {
            'left_pages':left_pages,
            'right_pages':right_pages,
            'current_page':current_page,
            'left_has_more':left_has_more,
            'right_has_more':right_has_more,
            'num_pages':num_pages,

        }


@method_decorator(permission_required(perm="news.add_news",login_url='/'),name='dispatch')
class WriteNews(View):
    def get(self,request):
        categories = NewsCategory.objects.all()
        context = {
            'categories': categories
        }
        return render(request,'cms/write_news.html',context=context)

    def post(self,request):
        form = WriteNewsForm(request.POST)
        if form.is_valid():
            #文章分类接收过来的是一个id
            #根据id 获取这个分类对象
            title =  form.cleaned_data.get('title')
            desc =form.cleaned_data.get('desc')
            thumbnail = form.cleaned_data.get('thumbnail')
            content = form.cleaned_data.get('content')
            category_id = form.cleaned_data.get('category')
            category = NewsCategory.objects.get(pk=category_id)
            News.objects.create(title=title,desc=desc,category=category,content=content,thumbnail=thumbnail,author=request.user)
            return restful.success()
        else:
            return restful.params_error(message=form.get_errors())

@permission_required(perm='news.view_newscategory',login_url='/')
def news_category(request):
    categories = NewsCategory.objects.all()
    context = {
        'categories':categories
    }
    return render(request,'cms/news_category.html',context=context)

@permission_required(perm='news.add_newscategory',login_url='/')
def add_news_category(request):
    name = request.POST.get('name')
    exists = NewsCategory.objects.filter(name=name).exists()
    if not exists:
        NewsCategory.objects.create(name=name)
        return restful.success()
    else:
        return restful.params_error(message='该分类已经存在')

import os
from django.conf import settings

def upload_file(request):
    file = request.FILES.get('file')
    name = file.name
    with open(os.path.join(settings.MEDIA_ROOT, name), 'wb') as fp:
        for chunk in file.chunks():
            fp.write(chunk)
    url = request.build_absolute_uri(settings.MEDIA_URL + name)
    return restful.result(data={'url':url})


@require_GET
def qntoken(request):
    access_key = 'p_p2-jutlTI1mlPCSfMEO8DyZnkQaiFrd9IOlvpz'
    secret_key = 'rN0YQux570vbhL5d8QvShrV-SnjzTdqhlfWstWri'
    q = qiniu.Auth(access_key, secret_key)

    bucket = 'manba888' #存储空间
    token = q.upload_token(bucket)
    print(token)
    return restful.result(data={"token":token})